package com.example.personal.aiagent.xunfei.account.mapper;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.personal.aiagent.common.util.TimeUtil;
import com.example.personal.aiagent.xunfei.account.model.entity.AccountEntity;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ListUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public interface AccountMapper extends BaseMapper<AccountEntity> {
    String ID = "ID";

    String USER_ID = "USER_ID";

    String APP_ID = "APP_ID";

    String API_SECRET = "API_SECRET";

    String API_KEY = "API_KEY";

    String MODIFY_TIMESTAMP = "MODIFY_TIMESTAMP";

    String MODIFY_TIME_DISPLAY = "MODIFY_TIME_DISPLAY";

    int MAX_QUERY_COUNT = 100;

    default int insertAccount(AccountEntity accountEntity) {
        int currentTime = TimeUtil.getCurTimeMs();
        String currentTimeString = TimeUtil.getTimeMsString(currentTime);
        accountEntity.setCreateTimestamp(currentTime);
        accountEntity.setModifyTimestamp(currentTime);
        accountEntity.setCreateTimeDisplay(currentTimeString);
        accountEntity.setModifyTimeDisplay(currentTimeString);
        return insert(accountEntity);
    }

    default int updateAccount(AccountEntity accountEntity) {
        UpdateWrapper<AccountEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set(USER_ID, accountEntity.getUserId());
        updateWrapper.set(APP_ID, accountEntity.getAppId());
        updateWrapper.set(API_SECRET, accountEntity.getApiSecret());
        updateWrapper.set(API_KEY, accountEntity.getApiKey());
        int currentTime = TimeUtil.getCurTimeMs();
        String currentTimeString = TimeUtil.getTimeMsString(currentTime);
        updateWrapper.set(MODIFY_TIMESTAMP, currentTime);
        updateWrapper.set(MODIFY_TIME_DISPLAY, currentTimeString);
        updateWrapper.eq(ID, accountEntity.getId());
        return update(null, updateWrapper);
    }

    default AccountEntity selectByUserId(int userId) {
        QueryWrapper<AccountEntity> entityQueryWrapper = new QueryWrapper<>();
        entityQueryWrapper.eq(USER_ID, userId);
        return selectOne(entityQueryWrapper);
    }

    default Map<Integer, AccountEntity> selectByUserIds(List<Integer> userIds) {
        List<List<Integer>> lists = ListUtils.partition(userIds, MAX_QUERY_COUNT);
        Map<Integer, AccountEntity> res = new HashMap<>();
        for (List<Integer> list : lists) {
            QueryWrapper<AccountEntity> entityQueryWrapper = new QueryWrapper<>();
            entityQueryWrapper.in(USER_ID, list);
            List<AccountEntity> entities = selectList(entityQueryWrapper);
            entities.forEach(it -> res.put(it.getUserId(), it));
        }
        return res;
    }
}
